/**
 * 项目详情V2页面JavaScript
 * 实现项目详情页面的交互功能
 */

// 使用命名空间模式避免全局变量污染
window.ProjectDetailV2 = (function() {
    'use strict';

    // 私有变量
    let projectId = null;
    let currentTab = 'tasks';
    let pagination = {
        tasks: { page: 1, limit: 10, total: 0 },
        members: { page: 1, limit: 10, total: 0 },
        logs: { page: 1, limit: 10, total: 0 }
    };

    // DOM缓存
    const elements = {};

    // 初始化函数
    function init() {
        // 从URL获取项目ID
        const pathParts = window.location.pathname.split('/');
        projectId = pathParts[pathParts.length - 2] || 1;

        // 缓存DOM元素
        cacheElements();
        
        // 绑定事件
        bindEvents();
        
        // 加载初始数据
        loadInitialData();
        
        // 初始化甘特图（如果需要）
        if (typeof initGanttChart === 'function') {
            initGanttChart();
        }
    }

    // 缓存DOM元素
    function cacheElements() {
        elements.tabButtons = document.querySelectorAll('.tab-button');
        elements.tabPanes = document.querySelectorAll('.tab-pane');
        elements.taskList = document.getElementById('task-list');
        elements.memberList = document.getElementById('member-list');
        elements.milestoneList = document.getElementById('milestone-list');
        elements.logList = document.getElementById('log-list');
        elements.taskPagination = document.getElementById('task-pagination');
        elements.memberPagination = document.getElementById('member-pagination');
        elements.logPagination = document.getElementById('log-pagination');
        elements.addTaskBtn = document.querySelector('.add-task-btn');
        elements.addMemberBtn = document.querySelector('.add-member-btn');
        elements.addMilestoneBtn = document.querySelector('.add-milestone-btn');
        elements.taskModal = document.getElementById('add-task-modal');
        elements.memberModal = document.getElementById('add-member-modal');
        elements.milestoneModal = document.getElementById('add-milestone-modal');
        elements.editMilestoneModal = document.getElementById('edit-milestone-modal');
        elements.deleteModal = document.getElementById('confirm-modal');
        elements.toastContainer = document.getElementById('toast-container') || createToastContainer();
    }

    // 绑定事件
    function bindEvents() {
        // 标签页切换
        elements.tabButtons.forEach(button => {
            button.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                switchTab(tabId);
            });
        });

        // 添加任务按钮
        if (elements.addTaskBtn) {
            elements.addTaskBtn.addEventListener('click', showAddTaskModal);
        }

        // 添加成员按钮
        if (elements.addMemberBtn) {
            elements.addMemberBtn.addEventListener('click', showAddMemberModal);
        }

        // 添加里程碑按钮
        if (elements.addMilestoneBtn) {
            elements.addMilestoneBtn.addEventListener('click', showAddMilestoneModal);
        }

        // 模态框关闭按钮
        document.querySelectorAll('.modal-close').forEach(button => {
            button.addEventListener('click', function() {
                const modal = this.closest('.modal');
                hideModal(modal);
            });
        });

        // 模态框背景点击关闭
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) {
                    hideModal(this);
                }
            });
        });

        // 表单提交
        const taskForm = document.getElementById('add-task-form');
        if (taskForm) {
            taskForm.addEventListener('submit', handleTaskSubmit);
        }

        const memberForm = document.getElementById('add-member-form');
        if (memberForm) {
            memberForm.addEventListener('submit', handleMemberSubmit);
        }

        const milestoneForm = document.getElementById('add-milestone-form');
        if (milestoneForm) {
            milestoneForm.addEventListener('submit', handleMilestoneSubmit);
        }

        const editMilestoneForm = document.getElementById('edit-milestone-form');
        if (editMilestoneForm) {
            editMilestoneForm.addEventListener('submit', handleEditMilestoneSubmit);
        }

        // 删除确认表单
        const deleteForm = document.getElementById('delete-form');
        if (deleteForm) {
            deleteForm.addEventListener('submit', handleDeleteSubmit);
        }
        
        // 保存任务按钮
        const saveTaskBtn = document.getElementById('save-task-btn');
        if (saveTaskBtn) {
            saveTaskBtn.addEventListener('click', function() {
                const form = document.getElementById('add-task-form');
                if (form) {
                    handleTaskSubmit({ preventDefault: () => {}, target: form });
                }
            });
        }
        
        // 保存成员按钮
        const saveMemberBtn = document.getElementById('save-member-btn');
        if (saveMemberBtn) {
            saveMemberBtn.addEventListener('click', function() {
                const form = document.getElementById('add-member-form');
                if (form) {
                    handleMemberSubmit({ preventDefault: () => {}, target: form });
                }
            });
        }
        
        // 保存里程碑按钮
        const saveMilestoneBtn = document.getElementById('save-milestone-btn');
        if (saveMilestoneBtn) {
            saveMilestoneBtn.addEventListener('click', function() {
                const form = document.getElementById('add-milestone-form');
                if (form) {
                    handleMilestoneSubmit({ preventDefault: () => {}, target: form });
                }
            });
        }
        
        // 保存编辑里程碑按钮
        const saveEditMilestoneBtn = document.getElementById('save-edit-milestone-btn');
        if (saveEditMilestoneBtn) {
            saveEditMilestoneBtn.addEventListener('click', function() {
                const form = document.getElementById('edit-milestone-form');
                if (form) {
                    handleEditMilestoneSubmit({ preventDefault: () => {}, target: form });
                }
            });
        }
        
        // 确认删除按钮
        const confirmDeleteBtn = document.getElementById('confirm-delete-btn');
        if (confirmDeleteBtn) {
            confirmDeleteBtn.addEventListener('click', function() {
                const form = document.getElementById('delete-form');
                if (form) {
                    handleDeleteSubmit({ preventDefault: () => {}, target: form });
                }
            });
        }
    }

    // 切换标签页
    function switchTab(tabId) {
        // 更新按钮状态
        elements.tabButtons.forEach(button => {
            if (button.getAttribute('data-tab') === tabId) {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            }
        });

        // 更新内容区域
        elements.tabPanes.forEach(pane => {
            if (pane.id === `${tabId}-tab`) {
                pane.classList.add('active');
                // 加载对应数据
                loadTabData(tabId);
            } else {
                pane.classList.remove('active');
            }
        });

        currentTab = tabId;
    }

    // 加载标签页数据
    function loadTabData(tabId) {
        switch (tabId) {
            case 'tasks':
                loadTasks();
                break;
            case 'members':
                loadMembers();
                break;
            case 'milestones':
                loadMilestones();
                break;
            case 'gantt':
                // 初始化甘特图
                if (typeof initGanttChart === 'function') {
                    initGanttChart();
                } else {
                    console.error('initGanttChart函数未定义');
                }
                break;
            case 'logs':
                loadLogs();
                break;
        }
    }

    // 加载初始数据
    function loadInitialData() {
        // 加载当前标签页的数据
        loadTabData(currentTab);
    }

    // 加载任务列表
    function loadTasks() {
        showLoading(elements.taskList);
        
        const params = new URLSearchParams({
            page: pagination.tasks.page,
            limit: pagination.tasks.limit
        });

        fetch(`/api/projects/${projectId}/tasks?${params}`)
            .then(response => response.json())
            .then(data => {
                pagination.tasks.total = data.total;
                renderTasks(data.tasks);
                renderPagination('tasks', elements.taskPagination, pagination.tasks);
            })
            .catch(error => {
                console.error('加载任务失败:', error);
                showError(elements.taskList, '加载任务失败，请刷新页面重试');
            });
    }

    // 渲染任务列表
    function renderTasks(tasks) {
        if (!tasks || tasks.length === 0) {
            elements.taskList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📋</div>
                    <div class="empty-state-title">暂无任务</div>
                    <div class="empty-state-text">点击"添加任务"按钮创建第一个任务</div>
                    <button class="btn btn-primary" onclick="ProjectDetailV2.showAddTaskModal()">
                        <span>➕</span> 添加任务
                    </button>
                </div>
            `;
            return;
        }

        const html = `
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>任务名称</th>
                            <th>负责人</th>
                            <th>开始日期</th>
                            <th>结束日期</th>
                            <th>状态</th>
                            <th>进度</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tasks.map(task => `
                            <tr>
                                <td>${task.name}</td>
                                <td>${task.assignee_name || '未分配'}</td>
                                <td>${formatDate(task.start_date)}</td>
                                <td>${formatDate(task.end_date)}</td>
                                <td>${getStatusBadge(task.status)}</td>
                                <td>
                                    <div class="progress-container">
                                        <div class="progress-bar">
                                            <div class="progress-fill" style="width: ${task.progress || 0}%"></div>
                                        </div>
                                        <div class="progress-text">
                                            <span>${task.progress || 0}%</span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="table-actions">
                                        <button class="btn btn-sm btn-outline" onclick="ProjectDetailV2.editTask(${task.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="ProjectDetailV2.deleteTask(${task.id}, '${task.name}')">删除</button>
                                    </div>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;

        elements.taskList.innerHTML = html;
    }

    // 加载成员列表
    function loadMembers() {
        showLoading(elements.memberList);
        
        const params = new URLSearchParams({
            page: pagination.members.page,
            limit: pagination.members.limit
        });

        fetch(`/api/projects/${projectId}/members?${params}`)
            .then(response => response.json())
            .then(data => {
                pagination.members.total = data.total;
                renderMembers(data.members);
                renderPagination('members', elements.memberPagination, pagination.members);
            })
            .catch(error => {
                console.error('加载成员失败:', error);
                showError(elements.memberList, '加载成员失败，请刷新页面重试');
            });
    }

    // 渲染成员列表
    function renderMembers(members) {
        if (!members || members.length === 0) {
            elements.memberList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">👥</div>
                    <div class="empty-state-title">暂无成员</div>
                    <div class="empty-state-text">点击"添加成员"按钮添加项目成员</div>
                    <button class="btn btn-primary" onclick="ProjectDetailV2.showAddMemberModal()">
                        <span>➕</span> 添加成员
                    </button>
                </div>
            `;
            return;
        }

        const html = `
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>姓名</th>
                            <th>角色</th>
                            <th>加入时间</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${members.map(member => `
                            <tr>
                                <td>${member.name}</td>
                                <td>${member.role}</td>
                                <td>${formatDate(member.join_date)}</td>
                                <td>${member.is_active ? '<span class="status-badge status-in-progress">活跃</span>' : '<span class="status-badge status-on-hold">非活跃</span>'}</td>
                                <td>
                                    <div class="table-actions">
                                        <button class="btn btn-sm btn-outline" onclick="ProjectDetailV2.editMember(${member.id})">编辑</button>
                                        <button class="btn btn-sm btn-danger" onclick="ProjectDetailV2.removeMember(${member.id}, '${member.name}')">移除</button>
                                    </div>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
        `;

        elements.memberList.innerHTML = html;
    }

    // 加载操作日志
    function loadLogs() {
        showLoading(elements.logList);
        
        const params = new URLSearchParams({
            page: pagination.logs.page,
            limit: pagination.logs.limit
        });

        fetch(`/api/projects/${projectId}/logs?${params}`)
            .then(response => response.json())
            .then(data => {
                pagination.logs.total = data.total;
                renderLogs(data.logs);
                renderPagination('logs', elements.logPagination, pagination.logs);
            })
            .catch(error => {
                console.error('加载日志失败:', error);
                showError(elements.logList, '加载日志失败，请刷新页面重试');
            });
    }

    // 渲染操作日志
    function renderLogs(logs) {
        if (!logs || logs.length === 0) {
            elements.logList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📝</div>
                    <div class="empty-state-title">暂无操作记录</div>
                    <div class="empty-state-text">项目暂无操作记录</div>
                </div>
            `;
            return;
        }

        const html = `
            <div class="timeline">
                ${logs.map(log => `
                    <div class="timeline-item">
                        <div class="timeline-marker ${getLogTypeClass(log.type)}"></div>
                        <div class="timeline-content">
                            <div class="timeline-header">
                                <span class="timeline-title">${log.title}</span>
                                <span class="timeline-time">${formatDateTime(log.created_at)}</span>
                            </div>
                            <div class="timeline-body">
                                <p>${log.description}</p>
                                <div class="timeline-user">操作人: ${log.user_name}</div>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;

        elements.logList.innerHTML = html;
    }

    // 渲染分页
    function renderPagination(type, container, paginationData) {
        if (!container) return;

        const { page, limit, total } = paginationData;
        const totalPages = Math.ceil(total / limit);

        if (totalPages <= 1) {
            container.innerHTML = '';
            return;
        }

        let html = '';

        // 上一页
        html += `<button class="pagination-item ${page <= 1 ? 'disabled' : ''}" 
                onclick="ProjectDetailV2.goToPage('${type}', ${page - 1})"
                ${page <= 1 ? 'disabled' : ''}>上一页</button>`;

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            // 显示当前页附近的页码
            if (i === 1 || i === totalPages || (i >= page - 2 && i <= page + 2)) {
                html += `<button class="pagination-item ${i === page ? 'active' : ''}" 
                        onclick="ProjectDetailV2.goToPage('${type}', ${i})">${i}</button>`;
            } else if (i === page - 3 || i === page + 3) {
                html += `<span class="pagination-item disabled">...</span>`;
            }
        }

        // 下一页
        html += `<button class="pagination-item ${page >= totalPages ? 'disabled' : ''}" 
                onclick="ProjectDetailV2.goToPage('${type}', ${page + 1})"
                ${page >= totalPages ? 'disabled' : ''}>下一页</button>`;

        container.innerHTML = html;
    }

    // 跳转到指定页
    function goToPage(type, page) {
        pagination[type].page = page;
        loadTabData(type);
    }

    // 显示添加任务模态框
    function showAddTaskModal() {
        if (!elements.taskModal) {
            console.error('任务模态框元素未找到');
            return;
        }
        
        // 重置表单
        const form = document.getElementById('add-task-form');
        if (form) {
            form.reset();
            // 设置默认值
            const statusSelect = form.querySelector('#status');
            if (statusSelect) {
                statusSelect.value = 'pending';
            }
            const prioritySelect = form.querySelector('#priority');
            if (prioritySelect) {
                prioritySelect.value = 'medium';
            }
            
            // 重置模态框标题和按钮
            const modalTitle = elements.taskModal.querySelector('.modal-header h3');
            if (modalTitle) {
                modalTitle.textContent = '添加任务';
            }
            
            const saveBtn = document.getElementById('save-task-btn');
            if (saveBtn) {
                saveBtn.textContent = '保存任务';
                // 移除旧的事件监听器并添加新的
                saveBtn.replaceWith(saveBtn.cloneNode(true));
                const newSaveBtn = document.getElementById('save-task-btn');
                newSaveBtn.addEventListener('click', function() {
                    const form = document.getElementById('add-task-form');
                    if (form) {
                        handleTaskSubmit({ preventDefault: () => {}, target: form });
                    }
                });
            }
        }
        
        showModal(elements.taskModal);
    }

    // 显示添加成员模态框
    function showAddMemberModal() {
        if (!elements.memberModal) {
            console.error('成员模态框元素未找到');
            return;
        }
        
        // 重置表单
        const form = document.getElementById('add-member-form');
        if (form) {
            form.reset();
            // 设置默认值
            const roleSelect = form.querySelector('#role');
            if (roleSelect) {
                roleSelect.value = 'member';
            }
        }
        
        showModal(elements.memberModal);
    }

    // 显示删除确认模态框
    function showDeleteModal(id, name, type) {
        if (!elements.deleteModal) {
            console.error('删除确认模态框元素未找到');
            return;
        }
        
        // 设置删除参数
        const idInput = document.getElementById('delete-id');
        const typeInput = document.getElementById('delete-type');
        const messageElement = document.getElementById('delete-message');
        
        if (idInput) idInput.value = id;
        if (typeInput) typeInput.value = type;
        
        // 设置确认消息
        let message = '';
        switch (type) {
            case 'task':
                message = `确定要删除任务"${name}"吗？此操作不可撤销。`;
                break;
            case 'member':
                message = `确定要移除成员"${name}"吗？`;
                break;
            case 'milestone':
                message = `确定要删除里程碑"${name}"吗？此操作不可撤销。`;
                break;
            default:
                message = `确定要删除"${name}"吗？此操作不可撤销。`;
        }
        
        if (messageElement) {
            messageElement.textContent = message;
        }
        
        showModal(elements.deleteModal);
    }

    // 处理任务表单提交
    function handleTaskSubmit(e) {
        e.preventDefault();
        
        const form = e.target || document.getElementById('add-task-form');
        if (!form) return;
        
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        // 添加项目ID
        data.project_id = projectId;
        
        // 验证必填字段
        if (!data.name) {
            showToast('请输入任务名称', 'error');
            return;
        }
        
        showLoading(elements.taskModal.querySelector('.modal-content'));
        
        fetch(`/api/projects/${projectId}/tasks`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(elements.taskModal.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.taskModal);
                showToast('任务添加成功', 'success');
                loadTasks();
            } else {
                showToast(data.message || '添加任务失败', 'error');
            }
        })
        .catch(error => {
            hideLoading(elements.taskModal.querySelector('.modal-content'));
            console.error('添加任务失败:', error);
            showToast('添加任务失败', 'error');
        });
    }

    // 处理成员表单提交
    function handleMemberSubmit(e) {
        e.preventDefault();
        
        const form = e.target || document.getElementById('add-member-form');
        if (!form) return;
        
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        // 验证必填字段
        if (!data.user_id) {
            showToast('请选择用户', 'error');
            return;
        }
        
        showLoading(elements.memberModal.querySelector('.modal-content'));
        
        fetch(`/api/projects/${projectId}/members`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(elements.memberModal.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.memberModal);
                showToast('成员添加成功', 'success');
                loadMembers();
            } else {
                showToast(data.message || '添加成员失败', 'error');
            }
        })
        .catch(error => {
            hideLoading(elements.memberModal.querySelector('.modal-content'));
            console.error('添加成员错误:', error);
            showToast('添加成员失败', 'error');
        });
    }

    // 处理删除表单提交
    function handleDeleteSubmit(e) {
        e.preventDefault();
        
        const form = e.target || document.getElementById('delete-form');
        if (!form) return;
        
        const idInput = form.querySelector('#delete-id');
        const typeInput = form.querySelector('#delete-type');
        
        if (!idInput || !typeInput) {
            showToast('删除参数不完整', 'error');
            return;
        }
        
        const id = idInput.value;
        const type = typeInput.value;
        
        if (!id || !type) {
            showToast('删除参数不完整', 'error');
            return;
        }
        
        showLoading(elements.deleteModal.querySelector('.modal-content'));
        
        // 根据类型构建不同的API端点
        let endpoint;
        switch (type) {
            case 'task':
                endpoint = `/api/tasks/${id}`;
                break;
            case 'member':
                endpoint = `/api/projects/${projectId}/members/${id}`;
                break;
            case 'milestone':
                endpoint = `/api/projects/${projectId}/milestones/${id}`;
                break;
            default:
                showToast('未知的删除类型', 'error');
                return;
        }
        
        fetch(endpoint, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            }
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(elements.deleteModal.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.deleteModal);
                showToast('删除成功', 'success');
                
                // 根据类型重新加载相应数据
                if (type === 'task') {
                    loadTasks();
                } else if (type === 'member') {
                    loadMembers();
                } else if (type === 'milestone') {
                    loadMilestones();
                }
            } else {
                showToast(data.message || '删除失败', 'error');
            }
        })
        .catch(error => {
            hideLoading(elements.deleteModal.querySelector('.modal-content'));
            console.error('删除错误:', error);
            showToast('删除失败', 'error');
        });
    }

    // 编辑任务
    function editTask(taskId) {
        // 获取任务数据
        fetch(`/api/tasks/${taskId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const task = data.task;
                    
                    // 填充表单
                    const form = document.getElementById('add-task-form');
                    if (form) {
                        form.querySelector('#task-name').value = task.name || '';
                        form.querySelector('#task-description').value = task.description || '';
                        form.querySelector('#assignee').value = task.assignee || '';
                        form.querySelector('#start-date').value = task.start_date || '';
                        form.querySelector('#end-date').value = task.end_date || '';
                        form.querySelector('#status').value = task.status || 'pending';
                        form.querySelector('#priority').value = task.priority || 'medium';
                        form.querySelector('#progress').value = task.progress || 0;
                        form.querySelector('#task-milestone').value = task.milestone_id || '';
                    }
                    
                    // 修改模态框标题
                    const modalTitle = elements.taskModal.querySelector('.modal-header h3');
                    if (modalTitle) {
                        modalTitle.textContent = '编辑任务';
                    }
                    
                    // 修改保存按钮文本
                    const saveBtn = document.getElementById('save-task-btn');
                    if (saveBtn) {
                        saveBtn.textContent = '更新任务';
                        // 移除旧的事件监听器并添加新的
                        saveBtn.replaceWith(saveBtn.cloneNode(true));
                        const newSaveBtn = document.getElementById('save-task-btn');
                        newSaveBtn.addEventListener('click', function() {
                            handleTaskEdit(taskId);
                        });
                    }
                    
                    // 显示模态框
                    showModal(elements.taskModal);
                } else {
                    showToast('error', '获取任务信息失败');
                }
            })
            .catch(error => {
                console.error('获取任务信息错误:', error);
                showToast('error', '获取任务信息失败');
            });
    }
    
    // 处理任务编辑
    function handleTaskEdit(taskId) {
        const form = document.getElementById('add-task-form');
        if (!form) return;
        
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        // 添加任务ID
        data.task_id = taskId;
        
        // 验证必填字段
        if (!data.name) {
            showToast('error', '请输入任务名称');
            return;
        }
        
        showLoading(elements.taskModal.querySelector('.modal-content'));
        
        fetch(`/api/tasks/${taskId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(elements.taskModal.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.taskModal);
                showToast('success', '任务更新成功');
                loadTasks(); // 重新加载任务列表
            } else {
                showToast('error', data.message || '更新任务失败');
            }
        })
        .catch(error => {
            hideLoading(elements.taskModal.querySelector('.modal-content'));
            console.error('更新任务错误:', error);
            showToast('error', '更新任务失败');
        });
    }

    // 删除任务
    function deleteTask(taskId, taskName) {
        showDeleteModal(taskId, taskName, 'task');
    }

    // 编辑成员
    function editMember(memberId) {
        // 这里可以实现编辑成员的逻辑
        showToast('info', '编辑功能正在开发中');
    }

    // 移除成员
    function removeMember(memberId, memberName) {
        showDeleteModal(memberId, memberName, 'member');
    }

    // 工具函数：显示模态框
    function showModal(modal) {
        if (modal) {
            modal.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
    }

    // 工具函数：隐藏模态框
    function hideModal(modal) {
        if (modal) {
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    }

    // 工具函数：重置表单
    function resetForm(formId) {
        const form = document.getElementById(formId);
        if (form) {
            form.reset();
        }
    }

    // 工具函数：显示加载状态
    function showLoading(container) {
        if (container) {
            container.innerHTML = `
                <div class="loading">
                    <div class="spinner"></div>
                    <span>加载中...</span>
                </div>
            `;
        }
    }

    // 工具函数：显示错误状态
    function showError(container, message) {
        if (container) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">⚠️</div>
                    <div class="empty-state-title">加载失败</div>
                    <div class="empty-state-text">${message}</div>
                    <button class="btn btn-primary" onclick="location.reload()">刷新页面</button>
                </div>
            `;
        }
    }

    // 工具函数：显示提示消息
    function showToast(message, type = 'info') {
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`;
        
        const icon = {
            success: '✅',
            error: '❌',
            warning: '⚠️',
            info: 'ℹ️'
        }[type] || 'ℹ️';
        
        toast.innerHTML = `
            <span class="toast-icon">${icon}</span>
            <span class="toast-message">${message}</span>
        `;
        
        elements.toastContainer.appendChild(toast);
        
        // 触发显示动画
        setTimeout(() => toast.classList.add('show'), 10);
        
        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }

    // 工具函数：创建提示容器
    function createToastContainer() {
        const container = document.createElement('div');
        container.id = 'toast-container';
        container.style.position = 'fixed';
        container.style.top = '1rem';
        container.style.right = '1rem';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
        return container;
    }

    // 工具函数：获取CSRF令牌
    function getCsrfToken() {
        const token = document.querySelector('meta[name="csrf-token"]');
        return token ? token.getAttribute('content') : '';
    }

    // 工具函数：格式化日期
    function formatDate(dateString) {
        if (!dateString) return '-';
        
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN');
    }

    // 工具函数：格式化日期时间
    function formatDateTime(dateString) {
        if (!dateString) return '-';
        
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }

    // 工具函数：获取状态标签
    function getStatusBadge(status) {
        const statusMap = {
            'planning': '<span class="status-badge status-planning">计划中</span>',
            'in-progress': '<span class="status-badge status-in-progress">进行中</span>',
            'completed': '<span class="status-badge status-completed">已完成</span>',
            'on-hold': '<span class="status-badge status-on-hold">暂停</span>',
            'cancelled': '<span class="status-badge status-cancelled">已取消</span>'
        };
        
        return statusMap[status] || '<span class="status-badge">未知</span>';
    }

    // 工具函数：获取日志类型样式
    function getLogTypeClass(type) {
        const typeMap = {
            'create': 'timeline-create',
            'update': 'timeline-update',
            'delete': 'timeline-delete',
            'comment': 'timeline-comment'
        };
        
        return typeMap[type] || 'timeline-default';
    }

    // 加载里程碑列表
    function loadMilestones() {
        showLoading(elements.milestoneList);
        
        fetch(`/api/projects/${projectId}/milestones`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderMilestones(data.milestones);
                } else {
                    showError(elements.milestoneList, data.message || '加载里程碑失败');
                }
            })
            .catch(error => {
                console.error('加载里程碑错误:', error);
                showError(elements.milestoneList, '加载里程碑失败');
            });
    }

    // 渲染里程碑列表
    function renderMilestones(milestones) {
        if (!milestones || milestones.length === 0) {
            elements.milestoneList.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">🚩</div>
                    <div class="empty-state-title">暂无里程碑</div>
                    <div class="empty-state-text">点击上方"添加里程碑"按钮创建第一个里程碑</div>
                    <button class="btn btn-primary" onclick="ProjectDetailV2.showAddMilestoneModal()">
                        <i class="fas fa-plus"></i> 添加里程碑
                    </button>
                </div>
            `;
            return;
        }

        const html = milestones.map(milestone => {
            const statusClass = getStatusClass(milestone.status);
            const statusText = getStatusText(milestone.status);
            const progressPercentage = parseInt(milestone.progress) || 0;
            
            return `
                <div class="milestone-item ${statusClass}">
                    <div class="milestone-top">
                        <h3 class="milestone-title">${milestone.name}</h3>
                        <div class="milestone-actions">
                            <button class="btn btn-sm btn-outline-primary" onclick="ProjectDetailV2.editMilestone('${milestone.id}')">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-outline-danger" onclick="ProjectDetailV2.deleteMilestone('${milestone.id}', '${milestone.name}')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="milestone-date">
                        <i class="fas fa-calendar-alt"></i>
                        ${formatDate(milestone.date)}
                    </div>
                    <div class="milestone-description">
                        ${milestone.description || '暂无描述'}
                    </div>
                    <div class="milestone-progress-container">
                        <div class="milestone-progress-label">
                            <span>进度</span>
                            <span>${progressPercentage}%</span>
                        </div>
                        <div class="milestone-progress-bar">
                            <div class="milestone-progress-fill" style="width: ${progressPercentage}%"></div>
                        </div>
                    </div>
                    <div class="milestone-status ${statusClass}">
                        ${statusText}
                    </div>
                </div>
            `;
        }).join('');

        elements.milestoneList.innerHTML = html;
    }

    // 显示添加里程碑模态框
    function showAddMilestoneModal() {
        resetForm('add-milestone-form');
        showModal(elements.milestoneModal);
    }

    // 显示编辑里程碑模态框
    function showEditMilestoneModal(milestoneId) {
        showLoading(elements.milestoneModal.querySelector('.modal-content'));
        
        fetch(`/api/projects/${projectId}/milestones/${milestoneId}`)
            .then(response => response.json())
            .then(data => {
                hideLoading(elements.milestoneModal.querySelector('.modal-content'));
                if (data.success) {
                    const milestone = data.milestone;
                    document.getElementById('edit-milestone-id').value = milestone.id;
                    document.getElementById('edit-milestone-name').value = milestone.name;
                    document.getElementById('edit-milestone-description').value = milestone.description || '';
                    document.getElementById('edit-milestone-start-date').value = milestone.start_date || '';
                    document.getElementById('edit-milestone-end-date').value = milestone.end_date || '';
                    
                    // 将英文状态转换为中文状态以匹配表单选项
                    let statusValue = milestone.status;
                    if (statusValue === 'pending') statusValue = '未开始';
                    else if (statusValue === 'in-progress') statusValue = '进行中';
                    else if (statusValue === 'completed') statusValue = '已完成';
                    else if (statusValue === 'delayed') statusValue = '已延期';
                    
                    document.getElementById('edit-milestone-status').value = statusValue;
                    document.getElementById('edit-milestone-progress').value = milestone.progress || 0;
                    
                    showModal(elements.editMilestoneModal);
                } else {
                    showToast('error', data.message || '获取里程碑信息失败');
                }
            })
            .catch(error => {
                hideLoading(elements.milestoneModal.querySelector('.modal-content'));
                console.error('获取里程碑信息错误:', error);
                showToast('error', '获取里程碑信息失败');
            });
    }

    // 处理里程碑表单提交
    function handleMilestoneSubmit(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const data = {
            name: formData.get('name'),
            description: formData.get('description'),
            date: formData.get('date'),
            status: formData.get('status'),
            progress: formData.get('progress')
        };
        
        showLoading(e.target.querySelector('.modal-content'));
        
        fetch(`/api/projects/${projectId}/milestones`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCsrfToken()
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(e.target.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.milestoneModal);
                showToast('success', '里程碑创建成功');
                loadMilestones(); // 重新加载里程碑列表
            } else {
                showToast('error', data.message || '创建里程碑失败');
            }
        })
        .catch(error => {
            hideLoading(e.target.querySelector('.modal-content'));
            console.error('创建里程碑错误:', error);
            showToast('error', '创建里程碑失败');
        });
    }

    // 处理里程碑编辑表单提交
    function handleEditMilestoneSubmit(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const milestoneId = formData.get('id');
        
        // 将中文状态转换为英文状态以匹配后端API
        let statusValue = formData.get('status');
        if (statusValue === '未开始') statusValue = 'pending';
        else if (statusValue === '进行中') statusValue = 'in-progress';
        else if (statusValue === '已完成') statusValue = 'completed';
        else if (statusValue === '已延期') statusValue = 'delayed';
        
        // 创建新的FormData对象，替换状态值
        const updatedFormData = new FormData();
        for (let [key, value] of formData.entries()) {
            if (key === 'status') {
                updatedFormData.append(key, statusValue);
            } else {
                updatedFormData.append(key, value);
            }
        }
        
        showLoading(e.target.querySelector('.modal-content'));
        
        // 使用更新后的FormData发送表单数据，与后端API期望的格式匹配
        fetch(`/api/projects/${projectId}/milestones/${milestoneId}`, {
            method: 'PUT',
            headers: {
                'X-CSRFToken': getCsrfToken()
            },
            body: updatedFormData  // 发送更新后的FormData对象
        })
        .then(response => response.json())
        .then(data => {
            hideLoading(e.target.querySelector('.modal-content'));
            if (data.success) {
                hideModal(elements.editMilestoneModal);
                showToast('success', '里程碑更新成功');
                loadMilestones(); // 重新加载里程碑列表
            } else {
                showToast('error', data.message || '更新里程碑失败');
            }
        })
        .catch(error => {
            hideLoading(e.target.querySelector('.modal-content'));
            console.error('更新里程碑错误:', error);
            showToast('error', '更新里程碑失败');
        });
    }

    // 删除里程碑
    function deleteMilestone(milestoneId, milestoneName) {
        showDeleteModal(milestoneId, milestoneName, 'milestone');
    }

    // 编辑里程碑
    function editMilestone(milestoneId) {
        showEditMilestoneModal(milestoneId);
    }

    // 工具函数：获取状态样式类
    function getStatusClass(status) {
        const statusMap = {
            'pending': '',
            'in-progress': 'in-progress',
            'completed': 'completed',
            'delayed': 'delayed'
        };
        
        return statusMap[status] || '';
    }

    // 工具函数：获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'pending': '待开始',
            'in-progress': '进行中',
            'completed': '已完成',
            'delayed': '已延期'
        };
        
        return statusMap[status] || '未知';
    }

    // 初始化甘特图
    function initGanttChart() {
        // 捕获并忽略浏览器扩展相关的错误
        const originalConsoleError = console.error;
        console.error = function(...args) {
            // 忽略来自浏览器扩展的错误
            if (typeof args[0] === 'string' && 
                (args[0].includes('content.js') || 
                 args[0].includes('runtime.lastError') ||
                 args[0].includes('remove listener'))) {
                return; // 忽略这些错误
            }
            // 其他错误正常输出
            originalConsoleError.apply(console, args);
        };
        
        console.log("初始化甘特图...");
        
        // 检查gantt对象是否可用
        if (typeof gantt === 'undefined') {
            console.error("gantt对象未定义，请确保dhtmlxgantt.js已正确加载");
            // 恢复原始console.error函数
            console.error = originalConsoleError;
            return;
        }
        
        try {
            // 设置日期格式 - 使用dhtmlxGantt的标准格式
            gantt.config.date_format = "%Y-%m-%d";
            
            // 添加中文本地化配置
            gantt.locale = {
                date: {
                    month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                    day_short: ["日", "一", "二", "三", "四", "五", "六"]
                },
                labels: {
                    new_task: "新任务",
                    icon_save: "保存",
                    icon_cancel: "取消",
                    icon_delete: "删除",
                    icon_details: "详情",
                    icon_edit: "编辑",
                    icon_add: "添加",
                    wdg_confirm: "确认",
                    wdg_cancel: "取消",
                    wdg_apply: "应用",
                    wdg_today: "今天",
                    wdg_tomorrow: "明天",
                    wdg_yesterday: "昨天",
                    wdg_hour: "小时",
                    wdg_minute: "分钟",
                    wdg_year: "年",
                    wdg_month: "月",
                    wdg_day: "日",
                    wdg_week: "周",
                    wdg_time: "时间",
                    wdg_period: "周期",
                    wdg_repeats: "重复",
                    wdg_every: "每个",
                    wdg_first: "第一个",
                    wdg_second: "第二个",
                    wdg_third: "第三个",
                    wdg_fourth: "第四个",
                    wdg_last: "最后一个",
                    wdg_workday: "工作日",
                    wdg_weekend: "周末",
                    wdg_start: "开始",
                    wdg_end: "结束",
                    wdg_after: "之后",
                    wdg_before: "之前",
                    wdg_on: "在",
                    wdg_the: "的",
                    wdg_repeat: "重复",
                    wdg_repeat_every: "重复每个",
                    wdg_repeat_on: "重复在",
                    wdg_repeat_end: "重复结束",
                    wdg_repeat_never: "从不",
                    wdg_repeat_on_date: "在日期",
                    wdg_repeat_after: "之后",
                    wdg_repeat_occurrences: "次",
                    wdg_daily: "每天",
                    wdg_weekly: "每周",
                    wdg_monthly: "每月",
                    wdg_yearly: "每年",
                    wdg_custom: "自定义",
                    wdg_close: "关闭",
                    wdg_ok: "确定",
                    wdg_delete: "删除",
                    wdg_save: "保存",
                    wdg_loading: "加载中...",
                    wdg_connection_error: "连接错误",
                    wdg_invalid_url: "无效的URL",
                    wdg_no_data: "没有数据",
                    wdg_confirm_deletion: "确认删除",
                    wdg_confirm_saving: "确认保存",
                    wdg_confirm_cancellation: "确认取消",
                    wdg_section_description: "描述",
                    wdg_section_time: "时间",
                    wdg_section_period: "周期",
                    wdg_columns_text: "任务名称",
                    wdg_columns_start_date: "开始日期",
                    wdg_columns_duration: "持续时间",
                    wdg_columns_add: "添加",
                    wdg_columns_priority: "优先级",
                    wdg_columns_type: "类型",
                    wdg_columns_owner: "负责人",
                    wdg_columns_options: "选项",
                    wdg_columns_progress: "进度",
                    wdg_columns_status: "状态",
                    wdg_gantt_chart: "甘特图",
                    wdg_grid_header: "任务列表",
                    wdg_timeline_header: "时间轴",
                    wdg_task_progress: "任务进度",
                    wdg_task_status: "任务状态",
                    wdg_task_owner: "任务负责人",
                    wdg_task_start: "任务开始",
                    wdg_task_end: "任务结束",
                    wdg_task_duration: "任务持续时间",
                    wdg_task_type: "任务类型",
                    wdg_task_priority: "任务优先级",
                    wdg_task_description: "任务描述",
                    wdg_task_options: "任务选项",
                    wdg_task_add: "添加任务",
                    wdg_task_edit: "编辑任务",
                    wdg_task_delete: "删除任务",
                    wdg_task_save: "保存任务",
                    wdg_task_cancel: "取消任务",
                    wdg_task_details: "任务详情",
                    wdg_task_progress_text: "进度",
                    wdg_task_status_text: "状态",
                    wdg_task_owner_text: "负责人",
                    wdg_task_start_text: "开始",
                    wdg_task_end_text: "结束",
                    wdg_task_duration_text: "持续时间",
                    wdg_task_type_text: "类型",
                    wdg_task_priority_text: "优先级",
                    wdg_task_description_text: "描述",
                    wdg_task_options_text: "选项",
                    wdg_task_add_text: "添加",
                    wdg_task_edit_text: "编辑",
                    wdg_task_delete_text: "删除",
                    wdg_task_save_text: "保存",
                    wdg_task_cancel_text: "取消",
                    wdg_task_details_text: "详情",
                    wdg_confirm_delete: "确定要删除这个任务吗？",
                    wdg_confirm_save: "确定要保存这个任务吗？",
                    wdg_confirm_cancel: "确定要取消编辑这个任务吗？",
                    wdg_loading_data: "正在加载数据...",
                    wdg_no_tasks: "没有任务",
                    wdg_task_added: "任务已添加",
                    wdg_task_updated: "任务已更新",
                    wdg_task_deleted: "任务已删除",
                    wdg_error_occurred: "发生错误",
                    wdg_invalid_data: "无效的数据",
                    wdg_required_field: "必填字段",
                    wdg_invalid_date: "无效的日期",
                    wdg_invalid_duration: "无效的持续时间",
                    wdg_invalid_priority: "无效的优先级",
                    wdg_invalid_status: "无效的状态",
                    wdg_invalid_type: "无效的类型",
                    wdg_invalid_owner: "无效的负责人",
                    wdg_invalid_description: "无效的描述",
                    wdg_invalid_options: "无效的选项",
                    wdg_field_required: "此字段是必填的",
                    wdg_field_invalid: "此字段无效",
                    wdg_field_date: "请输入有效的日期",
                    wdg_field_duration: "请输入有效的持续时间",
                    wdg_field_priority: "请输入有效的优先级",
                    wdg_field_status: "请输入有效的状态",
                    wdg_field_type: "请输入有效的类型",
                    wdg_field_owner: "请输入有效的负责人",
                    wdg_field_description: "请输入有效的描述",
                    wdg_field_options: "请输入有效的选项"
                }
            };
            
            // 设置中文本地化
            gantt.i18n.setLocale("cn");
            
            // 配置日期显示格式（使用新版scale配置）
            gantt.config.scales = [
                {unit: "month", step: 1, format: "%Y年%m月"},
                {unit: "day", step: 1, format: "%d"}
            ];
            
            // 设置日期格式
            gantt.config.date_format = "%Y-%m-%d";
            gantt.config.xml_date = "%Y-%m-%d";
            
            // 添加缺失的重要配置项
            gantt.config.scale_height = 60;  // 增加时间刻度高度以适应新的样式
            gantt.config.task_height = 30;
            gantt.config.row_height = 40;
            gantt.config.add_column = false;
            gantt.config.autosize = "y";
            gantt.config.details_on_create = true;
            gantt.config.details_on_dblclick = true;
            gantt.config.correct_work_time = false;
            gantt.config.round_dnd_dates = false;
            
            // 设置时间轴单元格的最小宽度
            gantt.config.min_column_width = 30;
            
            // 添加明确的列配置
            gantt.config.columns = [
                {name: "text", label: "任务名称", width: 250, tree: true, template: function(obj) {
                    return obj.name || obj.text || "未命名任务";
                }},
                {name: "milestone", label: "关联里程碑", width: 150, align: "center", template: function(obj) {
                    if (obj.type === "milestone") {
                        return "里程碑";
                    }
                    if (obj.milestone_id) {
                        // 查找对应的里程碑名称
                        const milestone = gantt.getTask("milestone_" + obj.milestone_id);
                        if (milestone) {
                            return milestone.name.replace("🏁 ", "");
                        }
                        return "里程碑 #" + obj.milestone_id;
                    }
                    return "未关联";
                }},
                {name: "start_date", label: "开始日期", width: 120, align: "center", template: function(obj) {
                    if (obj.start_date) {
                        const date = gantt.date.parseDate(obj.start_date, gantt.config.date_format);
                        return gantt.date.date_to_str("%Y-%m-%d")(date);
                    }
                    return "";
                }},
                {name: "duration", label: "持续时间", width: 80, align: "center"},
                {name: "progress", label: "进度", width: 60, align: "center", template: function(obj) {
                    return Math.round((obj.progress || 0) * 100) + "%";
                }},
                {name: "add", label: "", width: 40}
            ];
            
            // 配置甘特图布局
            gantt.config.layout = {
                css: "gantt_container",
                cols: [
                    {
                        width: 730,
                        min_width: 730,
                        rows: [
                            {view: "grid", scrollX: "gridScroll", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "gridScroll", group: "horizontal"}
                        ]
                    },
                    {resizer: true, width: 1},
                    {
                        rows: [
                            {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "scrollHor", group: "horizontal"}
                        ]
                    },
                    {view: "scrollbar", id: "scrollVer", group: "vertical"}
                ]
            };
            
            // 配置滚动条
            gantt.config.show_links = true;
            gantt.config.show_grid = true;
            gantt.config.show_chart = true;
            
            // 确保网格区域不水平滚动
            gantt.config.grid_resize = false;
            
            // 隐藏网格区域的水平滚动条
            gantt.attachEvent("onGanttReady", function() {
                // 隐藏网格区域的水平滚动条
                var gridHorScroll = document.querySelector('.gantt_grid .gantt_hor_scroll');
                if (gridHorScroll) {
                    gridHorScroll.style.display = 'none';
                }
                
                // 确保时间线区域显示水平滚动条
                var timelineHorScroll = document.querySelector('.gantt_timeline .gantt_hor_scroll');
                if (timelineHorScroll) {
                    timelineHorScroll.style.display = 'block';
                }
            });
            
            // 自定义任务工具提示
            gantt.templates.tooltip_text = function(start, end, task) {
                let tooltip = "<b>任务:</b> " + (task.name || task.text || "未命名任务") + 
                       "<br/><b>负责人:</b> " + (task.assignee || "未分配") +
                       "<br/><b>状态:</b> " + (task.status || "未设置") +
                       "<br/><b>进度:</b> " + Math.round((task.progress || 0) * 100) + "%";
                
                // 添加里程碑信息
                if (task.type === "milestone") {
                    tooltip += "<br/><b>类型:</b> 里程碑";
                } else if (task.milestone_id) {
                    // 查找对应的里程碑名称
                    const milestone = gantt.getTask("milestone_" + task.milestone_id);
                    if (milestone) {
                        tooltip += "<br/><b>关联里程碑:</b> " + milestone.name.replace("🏁 ", "");
                    } else {
                        tooltip += "<br/><b>关联里程碑:</b> #" + task.milestone_id;
                    }
                } else {
                    tooltip += "<br/><b>关联里程碑:</b> 未关联";
                }
                
                return tooltip;
            };
            
            // 自定义任务颜色
            gantt.templates.task_class = function(start, end, task) {
                // 里程碑特殊处理
                if (task.type === "milestone") {
                    return "gantt_milestone";
                }
                
                // 为关联了里程碑的任务添加特殊样式
                let cssClass = "";
                if (task.milestone_id) {
                    cssClass += "gantt_task_with_milestone ";
                }
                
                // 普通任务根据状态设置颜色
                if (task.status === "已完成") {
                    cssClass += "gantt_task_complete";
                } else if (task.status === "进行中") {
                    cssClass += "gantt_task_in_progress";
                } else if (task.status === "已延期") {
                    cssClass += "gantt_task_overdue";
                } else {
                    cssClass += "gantt_task_not_started";
                }
                
                return cssClass;
            };
            
            // 自定义里程碑样式
            gantt.templates.task_row_class = function(start, end, task) {
                if (task.type === "milestone") {
                    return "milestone_row";
                }
                return "";
            };
            
            // 自定义里程碑显示
            gantt.templates.task_text = function(start, end, task) {
                if (task.type === "milestone") {
                    return task.name || task.text || "里程碑";
                }
                return task.name || task.text || "未命名任务";
            };
            
            // 添加任务展开/收起事件监听
            gantt.attachEvent("onTaskOpen", function(id) {
                console.log("任务展开:", id);
                // 延迟保存状态, 确保甘特图已更新
                setTimeout(saveTaskOpenState, 100);
                return true;
            });
            
            gantt.attachEvent("onTaskClose", function(id) {
                console.log("任务收起:", id);
                // 延迟保存状态, 确保甘特图已更新
                setTimeout(saveTaskOpenState, 100);
                return true;
            });
            
            // 初始化甘特图
            var container = document.getElementById("gantt_here");
            if (!container) {
                console.error("甘特图容器不存在");
                return;
            }
            
            console.log("甘特图容器尺寸:", container.offsetWidth, "x", container.offsetHeight);
            
            // 确保容器有足够的尺寸
            if (container.offsetWidth < 100 || container.offsetHeight < 100) {
                console.warn("甘特图容器尺寸过小，尝试调整尺寸");
                container.style.width = "100%";
                container.style.height = "765px";
                console.log("调整后甘特图容器尺寸:", container.offsetWidth, "x", container.offsetHeight);
            }
            
            // 初始化甘特图
            gantt.init("gantt_here");
            console.log("甘特图初始化完成");
            
            // 加载项目甘特图数据
            loadProjectGantt();
            
            // 添加窗口大小变化时的自适应处理
            window.addEventListener('resize', function() {
                // 延迟执行以确保DOM更新完成
                setTimeout(function() {
                    gantt.render();
                    
                    // 调整甘特图容器大小以适应内容
                    const container = document.getElementById("gantt_here");
                    if (container) {
                        // 获取甘特图实际需要的宽度
                        const gridWidth = document.querySelector('.gantt_grid')?.offsetWidth || 730;
                        const timelineWidth = document.querySelector('.gantt_timeline')?.offsetWidth || 600;
                        const totalWidth = gridWidth + timelineWidth + 1; // +1 for resizer
                        
                        // 如果容器宽度不足以显示所有内容，增加容器宽度
                        if (container.offsetWidth < totalWidth) {
                            container.style.width = totalWidth + 'px';
                            console.log("窗口大小变化，调整甘特图容器宽度为:", totalWidth + 'px');
                        }
                        
                        // 重新渲染甘特图以应用新尺寸
                        gantt.render();
                    }
                }, 100);
            });
        } catch (e) {
            console.error("甘特图配置失败:", e);
            var container = document.getElementById("gantt_here");
            if (container) {
                container.innerHTML = '<div class="text-center py-12"><p class="text-red-500">甘特图配置失败: ' + e.message + '</p></div>';
            }
        } finally {
            // 恢复原始console.error函数
            console.error = originalConsoleError;
        }
    }

    // 加载项目甘特图数据
    function loadProjectGantt() {
        if (!projectId) {
            console.error("项目ID未设置");
            return;
        }
        
        console.log("加载项目甘特图数据，项目ID:", projectId);
        
        fetch(`/gantt/data/${projectId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log("甘特图数据:", data);
                
                // 确保gantt对象可用
                if (typeof gantt === 'undefined') {
                    console.error("gantt对象未定义");
                    return;
                }
                
                // 处理任务数据，确保name和text字段都存在
                if (data.data && Array.isArray(data.data)) {
                    data.data.forEach(task => {
                        if (!task.name && task.text) {
                            task.name = task.text;
                        } else if (!task.text && task.name) {
                            task.text = task.name;
                        }
                        
                        // 确保里程碑有正确的类型标识
                        if (task.type === "milestone") {
                            // 里程碑特殊处理
                            if (!task.duration) {
                                task.duration = 1; // 里程碑默认持续1天
                            }
                        }
                    });
                }
                
                // 解析数据到甘特图
                gantt.parse(data);
                
                // 恢复任务展开状态
                restoreTaskOpenState();
                
                // 调整视图以显示所有任务
                setTimeout(function() {
                    // 使用showDate和adjustViewport替代fitToContent
                    if (data.data && data.data.length > 0) {
                        // 找到最早和最晚的日期
                        var minDate = null;
                        var maxDate = null;
                        
                        data.data.forEach(function(task) {
                            if (task.start_date) {
                                var startDate = gantt.date.parseDate(task.start_date, gantt.config.date_format);
                                if (!minDate || startDate < minDate) {
                                    minDate = startDate;
                                }
                            }
                            
                            if (task.end_date) {
                                var endDate = gantt.date.parseDate(task.end_date, gantt.config.date_format);
                                if (!maxDate || endDate > maxDate) {
                                    maxDate = endDate;
                                }
                            }
                        });
                        
                        if (minDate) {
                            // 在最早日期前添加一些缓冲
                            var bufferDate = gantt.date.add(minDate, -5, "day");
                            gantt.showDate(bufferDate);
                        }
                    }
                    
                    // 调整视图
                    gantt.adjustViewport();
                }, 100);
                
                // 调整甘特图容器大小
                setTimeout(function() {
                    const container = document.getElementById("gantt_here");
                    if (container) {
                        // 获取甘特图实际需要的宽度
                        const gridWidth = document.querySelector('.gantt_grid')?.offsetWidth || 730;
                        const timelineWidth = document.querySelector('.gantt_timeline')?.offsetWidth || 600;
                        const totalWidth = gridWidth + timelineWidth + 1; // +1 for resizer
                        
                        // 如果容器宽度不足以显示所有内容，增加容器宽度
                        if (container.offsetWidth < totalWidth) {
                            container.style.width = totalWidth + 'px';
                            console.log("调整甘特图容器宽度为:", totalWidth + 'px');
                        }
                        
                        // 重新渲染甘特图以应用新尺寸
                        gantt.render();
                    }
                }, 200);
                
                // 处理滚动条
                setTimeout(function() {
                    // 确保网格区域不水平滚动
                    var gridHorScroll = document.querySelector('.gantt_grid .gantt_hor_scroll');
                    if (gridHorScroll) {
                        gridHorScroll.style.display = 'none';
                    }
                    
                    // 确保时间线区域显示水平滚动条
                    var timelineHorScroll = document.querySelector('.gantt_timeline .gantt_hor_scroll');
                    if (timelineHorScroll) {
                        timelineHorScroll.style.display = 'block';
                    }
                }, 300);
            })
            .catch(error => {
                console.error('加载甘特图数据失败:', error);
                var container = document.getElementById("gantt_here");
                if (container) {
                    container.innerHTML = '<div class="text-center py-12"><p class="text-red-500">加载甘特图数据失败: ' + error.message + '</p></div>';
                }
            });
    }

    // 保存任务展开状态
    function saveTaskOpenState() {
        if (typeof gantt === 'undefined') return;
        
        try {
            var openTasks = [];
            gantt.eachTask(function(task) {
                if (task.$open === false) {
                    openTasks.push(task.id);
                }
            });
            
            localStorage.setItem('gantt_open_tasks_' + projectId, JSON.stringify(openTasks));
        } catch (e) {
            console.error('保存任务展开状态失败:', e);
        }
    }

    // 恢复任务展开状态
    function restoreTaskOpenState() {
        if (typeof gantt === 'undefined') return;
        
        try {
            var openTasks = localStorage.getItem('gantt_open_tasks_' + projectId);
            if (openTasks) {
                openTasks = JSON.parse(openTasks);
                
                // 延迟执行，确保甘特图已完全加载
                setTimeout(function() {
                    openTasks.forEach(function(taskId) {
                        var task = gantt.getTask(taskId);
                        if (task) {
                            task.$open = false;
                            gantt.updateTask(taskId);
                        }
                    });
                }, 100);
            }
        } catch (e) {
            console.error('恢复任务展开状态失败:', e);
        }
    }

    // 公开API
    return {
        init: init,
        switchTab: switchTab,
        goToPage: goToPage,
        showAddTaskModal: showAddTaskModal,
        showAddMemberModal: showAddMemberModal,
        editTask: editTask,
        deleteTask: deleteTask,
        editMember: editMember,
        removeMember: removeMember,
        showAddMilestoneModal: showAddMilestoneModal,
        editMilestone: editMilestone,
        deleteMilestone: deleteMilestone,
        initGanttChart: initGanttChart
    };
})();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    ProjectDetailV2.init();
});